<template>
  <div>
    <div class="bard-info-header">
      <el-image
          class="bard-cover"
          :src="bardInfo?.cover"
          fit="cover"
      ></el-image>
      <div class="bard-info-overlay">
        <h1 class="bard-name">{{ bardInfo?.bardName }}</h1>
        <div style="display: flex;justify-content: space-between">
          <el-space>
              <span>
                <el-icon><User/></el-icon>
                <span>{{ bardInfo?.followerCount || 0 }} 关注</span>
              </span>
            <span>
                <el-icon><Document/></el-icon>
                <span>{{ bardInfo?.postCount || 0 }} 帖子</span>
              </span>
            <span>
                <el-icon><Calendar/></el-icon>
                <span>{{ dateFormat(bardInfo?.createTime) }}</span>
              </span>
          </el-space>
          <div>
            <el-button icon="EditPen" type="primary">发布新贴</el-button>
            <el-button icon="Plus" @click="followBard" v-if="!bardInfo?.isFollow">关注</el-button>
            <el-button icon="Plus" v-else @click="delFollow(bardInfo.bardId)">取消关注</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-center">
      <el-row class="bard-detail-page" :gutter="20">
        <el-col :span="15">
          <!-- 左侧帖子列表 -->
          <div class="posts-container">
            <div style="display: flex;justify-content: space-between">
              <h4>本吧推荐</h4>
              <el-radio-group v-model="postQuery.sortBy">
                <el-radio-button value="">综合</el-radio-button>
                <el-radio-button value="like_count">最热</el-radio-button>
                <el-radio-button value="create_time">最新</el-radio-button>
              </el-radio-group>
            </div>
            <!-- 帖子列表 -->
            <div v-if="postPage.list && postPage.list.length > 0">
              <div class="box" style="margin-top: 10px" v-for="(item, index) in postPage.list"
                   @click="goPostDetail(item.postId)">
                <div class="post-header">
                  <el-avatar
                      :src="item.avatar"
                      :size="48"
                  ></el-avatar>
                  <div class="post-user-info">
                    <h3 class="user-name">{{ item.nickname }}</h3>
                    <p class="post-time">{{ dateFormat(item.createdTime) }}</p>
                  </div>
                </div>
                <h2 class="post-title">{{ item.title }}</h2>
                <p class="post-content">{{ item.content }}</p>
                <!-- 帖子图片 -->
                <div class="post-images" v-if="item.files && item.files.length > 0">
                  <el-image
                      v-for="(file, idx) in item.files"
                      :key="idx"
                      :src="file.fileUrl"
                      :style="{ width: imageWidth(item.files.length) }"
                      fit="cover"
                      class="post-image"
                      v-if="isImageFileType(file?.fileType)"
                  ></el-image>
                </div>
                <!-- 帖子标签 -->
                <div class="post-tags" v-if="item.tags && item.tags.length > 0">
                  <el-tag
                      v-for="tag in item.tags"
                      :key="tag.tagId || tag.tagName"
                      type="info"
                  >
                    {{ tag.tagName }}
                  </el-tag>
                </div>

                <!-- 帖子互动数据 -->
                <div class="post-actions">
                <span class="action-item">
                  <el-icon><IconThumb/></el-icon>
                  <span>{{ item.likes || 0 }}</span>
                </span>
                  <span class="action-item">
                  <el-icon><ChatDotRound/></el-icon>
                  <span>{{ item.remarks || 0 }}</span>
                </span>
                  <span class="action-item">
<!--                  <el-icon><EyeFilled /></el-icon>-->
                  <span>{{ item.views || 0 }}</span>
                </span>
                </div>
                <!-- 无帖子状态 -->
              </div>
            </div>
            <div v-else class="empty-state">
              <el-empty description="暂无帖子"></el-empty>
            </div>
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                  background
                  layout="prev, pager, next, jumper"
                  v-model:current-page="postQuery.pageNum"
                  v-model:page-size="postQuery.pageSize"
                  :total="total"
                  @size-change="onPageSizeChange"
                  @current-change="onCurrentPageChange"
              />
            </div>
          </div>

        </el-col>
        <el-col :span="8">
          <el-card class="follow-card" shadow="hover">
            <template #header>
              活跃吧友
            </template>
            <div>
              <el-row class="box" v-for="item in forumUserPage.list">
                <el-col :span="8">
                  <el-avatar
                      :src="item.avatar"
                      :size="48"
                  ></el-avatar>
                </el-col>
                <el-col :span="16">
                  <div class="user-info">
                    <h3 class="user-name">{{ item.nickname }}</h3>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-card>
          <!-- 右侧发布帖子表单 -->
          <div class="post-form-container" v-if="isLogin">
            <el-card class="post-form-card" shadow="hover">
              <div class="form-header">
                <h3 class="form-title">发布新帖</h3>
              </div>
              <el-form :model="createPost" ref="caretPostFormRef" :rules="rules">
                <el-form-item prop="title">
                  <el-input
                      v-model="createPost.title"
                      placeholder="请输入标题（最多50字）"
                      maxlength="50"
                      show-word-limit
                      class="title-input"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="categoryId">
                  <el-cascader v-model="createPost.categoryId" placeholder="选择分类"
                               :options="categoryTree" clearable :props="categoryProps"/>
                </el-form-item>
                <el-form-item prop="tags">
                  <div class="tags-input-container">
                    <el-tag
                        v-for="tag in createPost.tags"
                        :key="tag.tagName"
                        closable
                        @close="removeTag(tag)"
                    >
                      {{ tag.tagName }}
                    </el-tag>
                    <el-input
                        v-model="inputTag"
                        placeholder="输入话题，按回车添加"
                        size="small"
                        @keyup.enter="pushTag"
                        class="tag-input"
                    ></el-input>
                  </div>
                </el-form-item>
                <el-form-item prop="content">
                  <!-- 内容输入 -->
                  <el-input
                      v-model="createPost.content"
                      type="textarea"
                      :autosize="{ minRows: 5, maxRows: 10 }"
                      placeholder="请输入帖子内容（最多1000字）"
                      maxlength="1000"
                      show-word-limit
                      class="content-input"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="uploadFileList">
                  <!-- 图片上传 -->
                  <div class="upload-container">
                    <UploadButtonNoView
                        scene-code="social:post"
                        @upload-file="upFile"
                    ></UploadButtonNoView>
                    <div class="preview-images" v-if="createPost.uploadFileList.length > 0">
                      <el-image
                          v-for="(file, idx) in createPost.uploadFileList"
                          :key="idx"
                          :src="file.fileUrl"
                          class="preview-image"
                          fit="cover"
                      >
                        <template #close>
                          <el-icon class="close-icon">
                            <Close/>
                          </el-icon>
                        </template>
                      </el-image>
                    </div>
                  </div>
                </el-form-item>
                <!-- 发布按钮 -->
                <el-button
                    type="primary"
                    :loading="postLoading"
                    :disabled="postLoading || !createPost.title || !createPost.content"
                    @click="submitPost"
                    class="submit-button"
                >
                  发布帖子
                </el-button>
              </el-form>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, computed, nextTick, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {Plus, Check, Close, User, Document, Calendar, ChatDotRound} from "@element-plus/icons-vue";
import type {SocPostCreateDTO, SocPostItemVO} from "@/api/social/posts/type";
import type {SocBardVO} from "@/api/social/bard/type";
import {reqGetPostPage, reqCreatePost, reqGetPostCategoryTreeList} from "@/api/social/posts";
import {reqGetBardById, reqFollowBard, reqDelFollowBard} from "@/api/social/bard";
import {useUserStore} from "@/stores/user";
import {isImageFileType} from "@/utils/file";
import UploadButtonNoView from "@/components/uploader/UploadButtonNoView.vue";
import type {UpFileDTO} from "@/components/uploader/UploadButtonNoView.vue";
import {storeToRefs} from "pinia";
import {reqGetForumUerInfoPage} from "@/api/social/forum/user";
import type {FormInstance} from "element-plus";

// 路由和状态管理
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const {isLogin} = storeToRefs(userStore);

// 响应式数据
const createPost = reactive<SocPostCreateDTO>({
  postId: "",
  userId: userStore.userId || "",
  bardId: route.query.bardId as string,
  schoolId: userStore.schoolId || "",
  categoryId: "",
  title: "",
  content: "",
  range: 0,
  status: 0,
  tags: [],
  synopsis: "",
  likes: 0,
  createdTime: null,
  updateTime: null,
  uploadFileList: [],
});
let categoryTree = ref([]);
let caretPostFormRef = ref()
const postQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  status: -1,
  bardId: route.query.bardId,
  sortBy: "",
  isAsc: true,
});
const inputTag = ref("");
const bardInfo = ref<SocBardVO>();
let postPage = reactive({
  pageNum: 1,
  total: 0,
  list: [] as SocPostItemVO[],
})
let forumUserPage = reactive({
  list: [],
  pageNum: 0,
  total: 0,
});
const total = ref<number>(0);
const followLoading = ref(false);
const postLoading = ref(false);
let categoryProps = {
  value: "categoryId",
  label: "name",
  children: "children",
  checkStrictly: true,
  emitPath: true
}

// 计算属性：根据图片数量计算图片宽度
const imageWidth = (count: number) => {
  if (count === 1) return "100%";
  if (count === 2 || count === 4) return "calc(50% - 8px)";
  return "calc(33.333% - 8px)";
};
let getCategoryTree = async () => {
  let res = await reqGetPostCategoryTreeList()
  categoryTree.value = res.data
};
// 格式化日期
const dateFormat = (timeStr: number | string | Date) => {
  if (!timeStr) return "";
  const time = new Date(timeStr);
  return time.toLocaleString();
};
let delFollow = (nardId: string) => {
  ElMessageBox.confirm(
      '确认取消关注吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '我再想想',
        type: 'warning',
      } as string
  )
      .then(async () => {
        await reqDelFollowBard(nardId)
        getBardInfo();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消成功',
        })
      })

}
let getForumUserPage = async () => {
  let res = await reqGetForumUerInfoPage({
    pageNum: 1,
    pageSize: 5,
    sortBy: '',
    bardId: route.query.bardId
  })
  Object.assign(forumUserPage, res.data)
}
// 获取贴吧信息
const getBardInfo = async () => {
  try {
    const res = await reqGetBardById(route.query.bardId as string);
    bardInfo.value = res.data;
  } catch (error) {
    ElMessage.error("获取贴吧信息失败");
  }
};

// 获取帖子列表
const getPostPage = async () => {
  try {
    if (postQuery.sortBy=='like_count'){
      postQuery.isAsc = false
    }
    const res = await reqGetPostPage(postQuery);
    Object.assign(postPage, res.data)
  } catch (error) {
    ElMessage.error("获取帖子列表失败");
  }
};

// 关注/取消关注贴吧
const followBard = async () => {
  if (!isLogin.value) {
    ElMessage.warning("请先登录");
    router.push("/login");
    return;
  }
  followLoading.value = true;
  try {
    await reqFollowBard({
      bardId: route.query.bardId as string
    });
    // 更新本地状态
    if (bardInfo.value) {
      bardInfo.value.isFollow = !(bardInfo.value.isFollow);
      if (bardInfo.value.isFollow) {
        bardInfo.value.followerCount = (bardInfo.value.followerCount || 0) + 1;
      } else {
        bardInfo.value.followerCount = Math.max(0, (bardInfo.value.followerCount || 0) - 1);
      }
    }
  } catch (error) {
    ElMessage.error("操作失败");
  } finally {
    followLoading.value = false;
  }
};

// 帖子相关操作
const goPostDetail = (postId: string) => {
  router.push({
    name: "post-detail",
    query: {postId},
  });
};

const pushTag = () => {
  if (inputTag.value?.trim()) {
    createPost.tags.push({tagName: inputTag.value.trim()});
    inputTag.value = "";
  }
};

const removeTag = (tag: { tagName: string }) => {
  createPost.tags = createPost.tags.filter(item => item.tagName !== tag.tagName);
};

// 上传文件处理
const upFile = (fileInfo: UpFileDTO) => {
  createPost.uploadFileList.push(fileInfo);
};

// 提交帖子
const submitPost = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      postLoading.value = true;
      try {
        await reqCreatePost(createPost);
        // 重置表单
        formReset();
        // 刷新数据
        getBardInfo();
        getPostPage();
        // 滚动到顶部
        window.scrollTo({top: 0, behavior: "smooth"});
      } catch (error) {
        ElMessage.error("发布失败");
      } finally {
        postLoading.value = false;
      }
    } else {
      console.log('error submit!', fields)
    }
  })

};

// 重置表单
const formReset = () => {
  Object.assign(createPost, {
    postId: "",
    userId: userStore.userId || "",
    bardId: route.query.bardId as string,
    schoolId: userStore.schoolId || "",
    categoryId: "",
    title: "",
    content: "",
    range: 0,
    status: 0,
    tags: [],
    synopsis: "",
    likes: 0,
    createdTime: null,
    updateTime: null,
    uploadFileList: [],
  });
  inputTag.value = "";
};

// 分页相关
const onPageSizeChange = (size: number) => {
  postQuery.pageSize = size;
  getPostPage();
};

const onCurrentPageChange = (page: number) => {
  postQuery.pageNum = page;
  getPostPage();
};

watch([() => postQuery.pageNum, () => postQuery.pageSize, () => postQuery.bardId,()=>postQuery.sortBy], () => {
  getPostPage();
})

// 生命周期钩子
onMounted(() => {
  getBardInfo();
  getPostPage();
  getForumUserPage()
  getCategoryTree()
});
let rules = reactive({
  title: [
    {required: true, message: '请输入标题', trigger: 'blur'},
    {min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  content: [
    {required: true, message: '请输入内容', trigger: 'blur'},
    {min: 2, max: 500, message: '内容长度在 2 到 500 个字符', trigger: 'blur'}
  ],
  categoryId: [
    {required: true, message: '请选择分类', trigger: 'change'}
  ],
  // tags: [
  //     {required: false, message: '请输入标签', trigger: 'blur'},
  //     {min: 0, max: 5, message: '标签长度在 0 到 5 个字符', trigger: 'blur'}
  // ]
})
</script>

<style scoped>
.bard-detail-page {
  width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.bard-info-header {
  position: relative;
  height: 240px;
}

.bard-cover {
  width: 100%;
  height: 100%;
}

.bard-info-overlay {
  max-width: 1400px;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  margin: 0 auto;
  padding: 20px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0));
  color: white;
}

.bard-name {
  margin: 0 0 10px;
  font-size: 24px;
  font-weight: 600;
}

.post-form-container {
  flex: 1;
}

.post-header {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-name {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.post-time {
  margin: 0;
  font-size: 12px;
  color: #888;
}

.post-title {
  margin: 0 0 10px;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.post-content {
  margin: 0 0 15px;
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.post-image {
  border-radius: 6px;
  overflow: hidden;
  height: 120px;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 15px;
}

.post-actions {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #888;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.empty-state {
  padding: 50px 0;
}

.pagination-container {
  margin-top: 30px;
  text-align: center;
}

.post-form-card {
  border-radius: 10px;
}

.form-header {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.form-title {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.form-content {
  padding: 20px;
}


.tags-input-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 40px;
}

.tag-input {
  flex: 1;
  min-width: 100px;
  border: none;
  outline: none;
}


.preview-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 15px;
}

.preview-image {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  position: relative;
}

.close-icon {
  position: absolute;
  top: 4px;
  right: 4px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  padding: 2px;
  cursor: pointer;
}

.submit-button {
  width: 100%;
  padding: 10px 0;
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .content-container {
    flex-direction: column;
  }
}

@media (max-width: 768px) {
  .bard-info-header {
    height: 180px;
  }

  .post-image {
    height: 80px;
  }

  .form-content {
    padding: 15px;
  }
}
</style>
